package com.example.status;

import com.example.model.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created with IntelliJ IDEA.
 * ClassName: StateTTL
 * Package: com.example.status
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-27
 * Time: 16:25
 */

//TTL 状态生存时间
public class StateTTL {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> map =
                env.socketTextStream("hadoop102", 7777)
                        .map(new MapFunction<String, WaterSensor>() {
                            @Override
                            public WaterSensor map(String value) throws Exception {
                                String[] s = value.split(" ");

                                return new WaterSensor(s[0], Long.valueOf(s[1]), Integer.valueOf(s[2]));
                            }
                        });

        //状态是在KeyBy之后
        map.keyBy(value -> value.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    ValueState<Integer> lastVc;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //在初始化方法中创建TTL
                        StateTtlConfig build = StateTtlConfig
                                //状态生存时间5秒就失效
                                .newBuilder(Time.seconds(5))
                                //策略 创建和 写(更新) 的时候才会刷新失效时间
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                //状态 读取 创建 写入 更新状态
                                // .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                                //状态可见性 从不返回过期的状态
                                .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                .build();

                        //2.状态描述去 启用TTL
                        ValueStateDescriptor<Integer> lastState = new ValueStateDescriptor<>("lastVc", Types.INT);
                        //将初始化的TTL 传进来
                        lastState.enableTimeToLive(build);
                        //初始化状态
                        this.lastVc = getRuntimeContext().getState(lastState);
                    }

                    //需求: 比较连续两次的水位值 大于10就输出
                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        //1.获取状态中的值 第一次获取状态值是null
                        Integer val = lastVc.value();
                        out.collect("Key = " + value.getId() + ",状态值 = " + val);

                        //更新
                        lastVc.update(value.getVc());

                    }
                }).print();


        env.execute();

    }
}
